import Parse from 'parse'
import { Button, Input } from 'antd'
import { useCallback, useEffect, useRef, useState } from 'react'
import { fd } from '../../utils'
import './index.scss'

const { TextArea } = Input

function ChatBox ({ curChat }) {
  const [content, setContent] = useState('')
  const [list, setList] = useState([])
  const refChatName = useRef(curChat)
  const firstLoad = useRef(true)
  const refList = useRef(list)
  const chatWindow = useRef(null)
  const listStatus = useRef({
    isMore: true,
    page: 1
  })
  const subCount = useRef(0)

  const init = async () => {
    await getInfos()
    await subCreate()
    subCount.current = 0
  }

  const bindScroll = useCallback(() => {
    const fdGetInfos = fd(getInfos)
    let x = null
    chatWindow.current && chatWindow.current.addEventListener('scroll', () => {
      let direction = 'up'
      let scrollTop = chatWindow.current.scrollTop
      if (x && x > scrollTop) direction = 'down'
      x = scrollTop
      if (scrollTop < 100 && direction === 'down') fdGetInfos()
    })
  }, [])

  const getInfos = async () => {
    if (!refChatName.current || !listStatus.current.isMore) return
    const Comment = Parse.Object.extend('Comment')
    const commentQuery = new Parse.Query(Comment)
    commentQuery.equalTo('chatName', refChatName.current)
    try {
      const listCount = await commentQuery.count()
      const skipNumber = listCount - 20 * listStatus.current.page
      commentQuery.skip(skipNumber < 0 ? 0 : skipNumber + subCount.current + 1)
      const limit = listCount - 20 * (listStatus.current.page - 1)
      commentQuery.limit((limit >= 20 ? 20 : limit) - subCount.current + 1)
      commentQuery.withCount()
      const res = await commentQuery.find()
      if (res.results.length > 0) {
        listStatus.current.page++
        const newList = [...res.results, ...refList.current]
        setList(newList)
        refList.current = newList
        if (refList.current.length >= listCount) listStatus.current.isMore = false
      }
    } catch (err) {
      console.error(err, '错误，请检查是否添加权限')
    }
  }

  useEffect(() => {
    if (!curChat) return
    subCount.current = 0
    firstLoad.current = true
    refChatName.current = curChat
    setList([])
    refList.current = []
    listStatus.current.page = 1
    listStatus.current.isMore = true
    void getInfos()
  }, [curChat])

  useEffect(() => {
    void init()
  }, [])

  useEffect(() => {
    bindScroll()
  }, [chatWindow.current])

  useEffect(() => {
    if (chatWindow.current && firstLoad.current && list.length > 0) {
      void moveBottom()
      firstLoad.current = false
    }
  }, [list])

  const moveBottom = async () => {
    if (!chatWindow.current) return
    const el = chatWindow.current
    el.scrollTop = 99999
  }

  const subCreate = async () => {
    const query = new Parse.Query('Comment')
    const subscription = await query.subscribe()
    subscription.on('create', (object) => {
      if (object.attributes.chatName !== refChatName.current) return
      subCount.current++
      console.log(subCount.current)
      const result = [...refList.current, object]
      setList(result)
      refList.current = result
      moveBottom()
    })
  }

  const createComment = async () => {
    const Comment = Parse.Object.extend('Comment')
    const comment = new Comment()
    const roleACL = new Parse.ACL()
    roleACL.setRoleReadAccess(curChat, true)
    roleACL.setReadAccess(Parse.User.current(), true)
    comment.setACL(roleACL)

    try {
      await comment.save({ content, author: Parse.User.current(), chatName: refChatName.current })
      setContent('')
    } catch (err) {
      console.error(err)
    }
  }

  const postMessage = async () => {
    if (!refChatName.current) return alert('未选择聊天室')
    if (!content.trim()) return alert('请输入内容')
    await createComment()
  }

  const page = <>
    <div className="title">{curChat}</div>
    <div className="infos" ref={chatWindow}>
      {list && list.map(item =>
        <div
          className={`info-item ${item.attributes.author.id === Parse.User.current().id ? 'right' : 'left'}`}
          key={item.id}
        >
          <div className="author">{item.attributes.author.id}</div>
          <div className="message">{item.attributes.content}</div>
        </div>
      )}
    </div>
    <div className="post-box">
      <TextArea
        className="post-content"
        rows={3}
        value={content}
        onKeyDown={({ keyCode }) => keyCode === 13 && postMessage()}
        onChange={({ target: { value } }) => setContent(value)}
      /> <Button className="post-btn" type="primary" onClick={postMessage} size="large">发送</Button>
    </div>
  </>

  const empty = <div>你还没选择聊天室</div>

  return <div className="chat-box-page">
    {curChat ? page : empty}
  </div>
}

export default ChatBox

